import Moudles from './Moudles'

class Runner {
  constructor() {
    this.algorithms = {}
    Moudles.map((m) =>
      m.then((moudle) => {
        const mou = moudle.default
        mou(this)
      })
    )
  }

  injectAlgorithm(name, algori) {
    this.algorithms[name] = algori
  }

  run(algori) {
    const resultEle = document.getElementById('result')
    const arrayEle = document.getElementById('txtArr')

    let values = arrayEle.value.split(',')
    values = values.map((item) => {
      return parseInt(item)
    })

    if (this.algorithms[algori]) {
      const func = this.algorithms[algori].algorithm
      const result = func(values)
      resultEle.innerText = result.join(', ')
    }
  }
}

function mountDesc() {
  const runner = window.runner
  const algorithms = runner.algorithms
  const ddlAlgori = document.getElementById('ddlAlgorithms')
  const eleTitle = document.getElementById('eleTitle')
  const eleDesc = document.getElementById('eleDescription')

  const seleIdx = ddlAlgori.selectedIndex
  const val = ddlAlgori.options[seleIdx].value
  const descs = algorithms[val].description

  var liHtml = ''
  descs.desc.forEach((item) => {
    liHtml += `<li>${item}</li>`
  })
  eleDesc.innerHTML = liHtml
  eleTitle.innerText = descs.title
}

function mountBtnEvent() {
  const runner = window.runner
  const btnEle = document.getElementById('btnRun')
  const ddlAlgori = document.getElementById('ddlAlgorithms')

  btnEle.addEventListener('click', () => {
    if (runner) {
      const seleIdx = ddlAlgori.selectedIndex
      const val = ddlAlgori.options[seleIdx].value
      runner.run(val)
    }
  })
}

function mountDDlOptions() {
  const runner = window.runner
  const algorithms = runner.algorithms
  const algoNames = Object.keys(algorithms)
  const ddlAlgori = document.getElementById('ddlAlgorithms')

  let optionsHtml = ''
  algoNames.forEach((item) => {
    let name = algorithms[item].description.title
    optionsHtml += `<option value='${item}'>${name}</option>`
  })
  ddlAlgori.innerHTML = optionsHtml
}

function mountDDlEvent() {
  const ddlAlgori = document.getElementById('ddlAlgorithms')
  const eleResult = document.getElementById('result')
  ddlAlgori.addEventListener('change', () => {
    mountDesc()
    eleResult.innerText = ''
  })
}

window.runner = new Runner()

window.addEventListener('load', () => {
  mountDDlOptions()
  mountDesc()

  mountBtnEvent()
  mountDDlEvent()
})
